package com.wx.registerclient.listener;

import com.wx.registerclient.configuration.NBServerConfigProperties;
import com.wx.registerclient.heartbeat.HeartBeat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

@Component
public class HeartBeatListener  implements ApplicationRunner {

    @Autowired
    private NBServerConfigProperties properties;
    @Autowired
    private HeartBeat heartBeat;
    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 连接异常计数器
        final ArrayList<Integer> countList=new ArrayList<>();
        countList.add(0);
        // 获得注册中心地址
        String registerPort = properties.getRegisterPort();
        String registerHost = properties.getRegisterHost();
        String url="http://"+registerHost+":"+registerPort+"/register/heartBeat";
        // 获得心跳的时间
        Integer heartBeatTime = properties.getHeartBeatTime();
        // 获得容忍次数
        Integer toleratedTimes = properties.getToleratedTimes();
        // 创建定时器
        Timer timer = new Timer();
        // 执行定时任务
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
              // 获得注册中心状态
                boolean serverStatus = heartBeat.getServerStatus(url);

                if(!serverStatus){
                    Integer integer = countList.get(0);
                    integer++;
                    countList.set(0,integer);
                }else {

                }
                // 判断计数器大小 Tolerated times
                Integer count = countList.get(0);
                if(count>toleratedTimes){

                    throw new RuntimeException("注册中心异常");
                }

            }
        },1000,heartBeatTime);
    }
}
